import { getLocalHistory, getTokenInfo } from '@/utils/storage'
import { applyMiddleware, legacy_createStore as createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import rootReducer from './reducers'
import { ThunkAction } from 'redux-thunk'
import { HomeAction } from './reducers/home'
import { LoginAction } from './reducers/login'
import { ProfileAction } from './reducers/profile'
import { SearchAction } from './reducers/search'
import { ArticleAction } from './reducers/article'
/*
ThunkAction<R,S,E,A>
S:需要指定getState的返回类型， RootState
A:需要指定Action的类型
R:thunk的action的返回类型 void Promise<void>
E:额外的参数类型：unknown
*/

// 创建 Store 实例
const store = createStore(
  // 参数一：根 reducer
  rootReducer,

  // 参数二：初始化时要加载的状态
  {
    login: getTokenInfo(),
    search: {
      suggestions: [],
      results: [],
      histories: getLocalHistory(),
    },
  },

  // 参数三：增强器
  composeWithDevTools(applyMiddleware(thunk))
)
// 获取RootState的类型
export type RootState = ReturnType<typeof store.getState>

type RootAction =
  | HomeAction
  | LoginAction
  | ProfileAction
  | SearchAction
  | ArticleAction

export type RootThunkAction = ThunkAction<
  Promise<void>,
  RootState,
  unknown,
  RootAction
>

// 导出 Store 实例
export default store
